<?php

class Controller_Transactions extends Controller_Template
{

    public function action_add()
    {
        $userid = Session::get('userid');
        If (Input::method() == 'POST')
        {
            //check money
            if (Input::post('money') <= 0)
            {
                Session::set_flash('message', 'Invalid money!');
                Response::redirect('transactions/add');
            }
            //create transaction
            $a = Input::post('money');
            $type = Input::post('type');
            $wallet = Input::post('wallet_id');
            $val = Model_Transaction::get_validation_add($val = Validation::forge()); //trong nay van thieu dk kiem tra trung email hay username vs ng khac
            if ($val->run())
            {
                $category = Model_Transaction::forge($val->validated());
                date_default_timezone_set('Asia/Saigon');
                $category->created = date('Y-m-d H:i:s');
                If ($category->save())
                {
                    
                    // Plus money depend type
                    if ($type == 1)
                    {
                        $query = "UPDATE tb_wallets as Wallet
                                        SET current_money = current_money +'$a',
                                            earn = earn+'$a'
                                        WHERE id='$wallet'";
                    } else
                    {
                        $query = "UPDATE tb_wallets as Wallet
                                        SET current_money = current_money -'$a',
                                            spent = spent+'$a'
                                        WHERE id='$wallet'";
                    }
//                    Debug::dump($query);
                    DB::query($query)->execute();
//                    echo DB::last_query();die();
                    Session::set_flash('message', 'The transactions has been added.');
                    Response::redirect('transactions/index');
                } else
                {
                    Session::set_flash('message', 'The transaction could not be saved. Please, try again.');
                }
            } else
            {
                Session::set_flash('message', $val->show_errors());
            }
        }
        //set input form before submit
        $type = 1;
        $data = Model_Category::query()->where('type', '=', $type)->and_where_open()->where('user_id', $userid)
                        ->or_where('status', '=', 1)->and_where_close()->get();
        $categories = array();
        foreach ($data as $item)
        {
            $categories[$item->id] = $item->name;
        }
        //set default wallet to defaul of select
        $data = Model_Wallet::query()->where('user_id', $userid)->order_by('status', 'DESC')->get();
        $wallets = array();
        foreach ($data as $item)
        {
            $wallets[$item->id] = $item->name;
        }
        $view = Fuel\Core\View::forge('transactions/add');
//        Fuel\Core\Debug::dump($categories);die;
        $view->option_category = $categories;
        $view->option_wallet = $wallets;
        $this->template->title = 'Transactions';
        $this->template->js = 'tr_add.js';
        $this->template->content = $view;
    }

    public function action_addchild()
    {
        $data["subnav"] = array('addchild' => 'active');
        $this->template->title = 'Transactions &raquo; Addchild';
        $this->template->content = View::forge('transactions/addchild', $data);
    }

    public function action_edit($id)
    {
        $userid = Session::get('userid');
        If (Input::method() == 'POST')
        {
            //check money
            if (Input::post('money') <= 0)
            {
                Session::set_flash('message', 'Invalid money!');
                Response::redirect('transactions/edit');
            }
            $data = Model_Transaction::find($id);
            //cannot change wallet of transaction that is spent on or earn from(similar money lover)
            if ($data->categories->name == 'Nợ' || $data->categories->name == 'Cho vay')
            {
                if ($data->wallet_id != Input::post('wallet_id'))
                {
                    Session::set_flash('message', 'Can not change wallet of transaction because that transaction  belong to spent or earn');
                    Response::redirect('transactions/edit');
                }
            }
            //save transaction
            $val = Model_Transaction::get_validation_add($val = Validation::forge()); //trong nay van thieu dk kiem tra trung email hay username vs ng khac
            if ($val->run())
            {
                $transaction = Model_Transaction::forge($val->validated());
                date_default_timezone_set('Asia/Saigon');
                $transaction->created = date('Y-m-d H:i:s');
                If ($transaction->save())
                {
                    $type = $data->categories->type;
                    $a = $data->money;
                    $wallet = $data->wallet_id;
                    //Reset updated Wallet 
                    if ($type == 0)
                    {
                        $query = "UPDATE tb_wallets as Wallet
                                           SET current_money = current_money -'$a',
                                               earn = earn-'$a'
                                           WHERE id='$wallet'";
                    } else
                    {
                        $query = "UPDATE tb_wallets as Wallet
                                           SET current_money = current_money +'$a',
                                               spent = spent-'$a'
                                           WHERE id='$wallet'";
                    }
                    DB::query($query)->execute();
                    //Update choosed Wallet
                    $type = Input::post('type');
                    $a = Input::post('money');
                    $wallet = Input::post('wallet_id');
                    //1:earn from,2 spent on
                    if ($type == 1)
                    {
                        $query = "UPDATE tb_wallets as Wallet
                                        SET current_money = current_money +'$a',
                                            earn = earn+'$a'
                                        WHERE id='$wallet'";
                    } else
                    {
                        $query = "UPDATE tb_wallets as Wallet
                                        SET current_money = current_money -'$a',
                                            spent = spent+'$a'
                                        WHERE id='$wallet'";
                    }
                    DB::query($query)->execute();
                    Session::set_flash('message', 'The transactions has been saved');
                    Response::redirect('transactions/index');
                } else
                {
                    Session::set_flash('message', 'The transactions can not  save');
                }
            } else
            {
                Session::set_flash('message', $val->show_errors());
            }
        }
            $transaction = Model_Transaction::find($id);
            //set wallet
            $data = Model_Wallet::query()->where('user_id', $userid)->order_by('status', 'DESC')->get();
            $wallets = array();
            foreach ($data as $item)
            {
                $wallets[$item->id] = $item->name;
            }
            //set categories.
            $transaction->categories->type = $transaction->categories->type + 1;
            $type = $transaction->categories->type;
            $data = Model_Category::query()->where('type', '=', $type)->and_where_open()->where('user_id', $userid)
                            ->or_where('status', '=', 1)->and_where_close()->get();
            $categories = array();
            foreach ($data as $item)
            {
                $categories[$item->id] = $item->name;
            }
            $view = View::forge('transactions/edit');
            $view->transaction = $transaction;
            $view->option_wallet = $wallets;
            $view->option_categories = $categories;
            $this->template->title = 'Transactions &raquo; Edit';
            $this->template->js = 'tr_add.js';
            $this->template->content = $view;
        
    }

    public function action_home()
    {
        $data["subnav"] = array('home' => 'active');
        $this->template->title = 'Transactions &raquo; Home';
        $this->template->content = View::forge('transactions/home', $data);
    }

    public function action_index()
    {
        $id = Session::get('userid');
        If (Input::method() == 'POST')
        {
            //laytime
            $y = Input::post('time.year'); 
            $m = Input::post('time.month'); 
            $d = Input::post('time.day'); ;
//            //kiem tra time null ko
            if ($y == null || $m == null || $d == null)
            {
                $time = null;
            } else
            {
                $time = $y . '-' . $m . '-' . $d; //de thanh dinh dang y-m-d
                //phai chuyen thanh string to time roi dung date thi moi so sanh dc trong sql 
                $time1 = date('Y-m-d H:i:s', strtotime($time));
                $time2 = date('Y-m-d', strtotime($time . ' +1 day'));
            }
            //lay kieu muc
               @$type = Input::post('type'); ; //de la 3 nhung debug o day type la null
//            //lay vi
              @$walletid =Input::post('wallet_id');
//            //lay muc
               @$categoryid = Input::post('category_id');
//            //debug($walletid);debug($categoryid); //cho nay chi can sua cai time la dc
                $conditions = array();
            if ($walletid != null)
            {
                $conditions['wallets.id'] = $walletid;
            } //dat 3 la null..de dung jquery set dc select.jquery ko set dc gia tri null
            if ($type != null)
            {
                $conditions['categories.id'] = $categoryid;
            }
            if ($time != null)
            {
                $conditions['transactions.updated >'] = $time1;
                $conditions['transactions.updated <'] = $time2;
            }
            $config = array(
                'pagination_url' => 'http://localhost/fuelphp-ml/public/transactions/index',
                'total_items' => Model_Transaction::count(),
                'per_page' => 5,
                'uri_segment' => 3,
            );
            $pagination = Pagination::forge('mypagination', $config);
            $transactions = Model_Transaction::query()->limit($pagination->per_page)->offset($pagination->offset)
                            ->related('wallets')->related('categories')->where($conditions)->get(); 
            //set type
            @$a = Input::post('type');
            @$b = Input::post('category_id');
            @$c = Input::post('wallet_id');
        } else
        {
            $user_id = Session::get('userid');
            $user_id=42;
            //set pagnitor
            $config = array(
                'pagination_url' => 'http://localhost/fuelphp-ml/public/transactions/index',
                'total_items' => Model_Transaction::count(),
                'per_page' => 5,
                'uri_segment' => 3,
            );
            $pagination = Pagination::forge('mypagination', $config);
            $transactions = Model_Transaction::query()->limit($pagination->per_page)->offset($pagination->offset)
                            ->related('wallets')->where('wallets.user_id', $id)->get(); 
        }
        //set lai thuoc tinh sau khi submit
            $view = View::forge('transactions/index');
            $type1 = @$a;
            $category_id1 = @$b;
            $wallet_id1 = @$c;
        //set  mac dinh vao trang..type mac dinh la 0:earn cho nay cong 1
        //neu ton tai $this->request data thi $type = cai day ko thi de la 1(mac dinh luc vao trang)
        if ($type1 == null)
        {
            $type = 1;
            
        } else
        {
            $type = $type1;  
            
        }
        //set types
        $types[1] = 'Earn';
        $types[2] = 'Spent';
        $types[3] = 'null';
        $type=$type-1;
        //set category dua vao type
        //$categories = $this->Transaction->Category->find('list', array('conditions' => array('Category.type' => $type, 'OR' => array('Category.user_id' => $id, 'Category.status' => 1))));
//        $categories=$data;
        $data = DB::query("
                               SELECT DISTINCT Category.id, Category.name
                                FROM tb_categories AS Category 
                                WHERE
                                    Category.type = '$type' 
                                AND((Category.user_id = '$id') OR (Category.status = 1) ) 
                          ")->execute();
//        Debug::dump( \DB::last_query());
        $categories = array();
        foreach ($data as $item)
        {
            $categories[$item['id']] = $item['name'];
        }
        //set wallet
        $data = Model_Wallet::query()->where('user_id', $id)->order_by('status', 'DESC')->get();
        $wallets = array();
        foreach ($data as $item)
        {
            $wallets[$item->id] = $item->name;
        }
        //\Fuel\Core\Debug::dump($wallets);die();
        //Debug::dump($categories);die;
        $view->transactions = $transactions;
        $view->type=$type+1;
        $view->category1=$category_id1;
        $view->option_type=$types;
        $view->option_category=$categories;
//        Debug::dump($category_id1);Debug::dump($categories);
        $view->option_wallet=$wallets;
        $this->template->title = 'Index Transactions page';
        $this->template->js = 'tr_add.js';
       // $this->template->css = 'tran_css.css';
        $this->template->set('content', $view, false);
    }

    public function action_typesetparents()
    {
        if (Input::is_ajax())
        {
            //get defaul category and current user's category
            $id = (int) Session::get('userid');
            $type = (int) Input::post('type');
            $type = $type - 1;
            $data = DB::query("
                               SELECT DISTINCT Category.id, Category.name
                                FROM tb_categories AS Category 
                                WHERE
                                    Category.type = '$type' 
                                AND Category.parent_id IS NULL  
                                AND((Category.user_id = '$id') OR (Category.status = 1) ) 
                                ")->execute();

            $listCategories = array();
            foreach ($data as $item)
            {
                $listCategories[$item['id']] = $item['name'];
            }
            echo json_encode($listCategories);
            return new Response(View::forge('transactions/typesetparents'));
        }
    }

    public function action_view($id=null)
    {
        
        $view= View::forge('transactions/view');
        $transaction=  Model_Transaction::find($id);
//        Debug::dump($transaction->categories->name);
        $this->template->title='View transactions';
        $view->transaction = $transaction;
        $this->template->content=$view;
    }

    public function action_isAuthorized()
    {
        $data["subnav"] = array('isAuthorized' => 'active');
        $this->template->title = 'Transactions &raquo; IsAuthorized';
        $this->template->content = View::forge('transactions/isAuthorized', $data);
    }
     public function action_delete($id = null)
    {
        
        //$this->Transaction->id = $id;
        //get information transaction deleted
        $transaction=  Model_Transaction::find($id);
        $type = $transaction->categories->type; //o day lay ra 0:thu,1 chi
        $a = $transaction->money;
        $wallet = $transaction->wallet_id;
//        Debug::dump($transaction->categories);// truoc khi delete  catethi la gia tri.transaction van gtri đó
        if ($transaction->delete())
        {
//            Debug::dump($transaction->categories);die();//sau khi delete thi cate la null,tran van gia ti do
            //after deleted ,update wallet.!
//            $type = $transaction->categories->type; //o day lay ra 0:thu,1 chi
//            $a = $transaction->money;
//            $wallet = $transaction->wallet_id;
            if ($type == 0)
            {  
                $query = "UPDATE tb_wallets as Wallet
                                       SET current_money = current_money -'$a',
                                           earn = earn-'$a'
                                       WHERE id='$wallet'";
            } else
            {
                $query = "UPDATE tb_wallets as Wallet
                                       SET current_money = current_money +'$a',
                                           spent = spent-'$a'
                                       WHERE id='$wallet'";
            }

            DB::query($query)->execute();
//            Debug::dump( DB::last_query());die;
            
            //check whether this transaction is a parent transaction
            //if this is a parent transaction,also delete child transaction
           if(@$transaction->child_transaction!=null)
            {
            Response::redirect('transactions/delete/'.$transaction->child_transaction->id);
            } 
            Session::set_flash('message', 'The transaction has been deleted');
        } else
        {
            Session::set_flash('message', 'The transaction could not save ');
        }
        return Response::redirect('transactions/index/');
    }

}
